import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { Istudent } from '../istudent';
 
@Directive({ selector: '[customNgFor]'})
export class CustomNgForDirective {
 
    @Input() itemRenderAtOnce = 1;
    @Input() renderInterval = 1500;
    @Input() maxSupportItems = 1000;
    @Input('customNgForOf')
    set aaaa(list: Istudent[]) {
        this.list = list;
        if (this.initialized) {
            this.viewContainerRef.clear();
            this.buildListProgressively();
        }
    }
 
    list: any[] = [];
    buildListInterval: ReturnType<typeof setInterval>|undefined;
    private initialized = false;
 
    constructor(private viewContainerRef: ViewContainerRef, private templateRef: TemplateRef<any>) {
        //
    }
 
    ngOnInit() {
        this.initialized = true;
        if (this.list && this.list.length > 0) {
            this.buildListProgressively();
        }
    }
 
    buildListProgressively() {
        const length = this.list?.length || 0;
        let currentIndex = 0;
 
        if (this.buildListInterval) {
            clearInterval(this.buildListInterval);
        }
 
        this.buildListInterval = setInterval(() => {
            const nextIndex = currentIndex + this.itemRenderAtOnce - 1;
 
            for (let n = currentIndex; n <= nextIndex; n++) {
                if (n >= length || n >= this.maxSupportItems) {
                    clearInterval(this.buildListInterval);
                    break;
                }
                this.viewContainerRef.createEmbeddedView(this.templateRef, {
                    $implicit: this.list[n],
                    index: n
                });
            }
 
            currentIndex += this.itemRenderAtOnce;
        }, this.renderInterval);
    }
}